package com.compass.mobile.ui.activity

import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.lifecycle.lifecycleScope
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.ActivityCaseHistoryBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.CASE_ADD
import com.compass.mobile.framework.constant.CASE_REPORT_ACTION
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.CodeUtils.getCodeUrl
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Attach
import com.compass.mobile.models.MedicalRecordReport
import com.compass.mobile.presenters.ReportUploadPresenter
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.PersonalCenterViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Description： 报告上传（病历上传）
 * Date:2024/6/20 16:53
 */
class ReportUploadActivity : BaseVBActivity<ActivityCaseHistoryBinding>() {

    private val personalCenterViewModel: PersonalCenterViewModel by viewModels()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var caseHistoryList: MutableList<MedicalRecordReport> = mutableListOf()
    private var mPage = 1
    private var isHaveNext = true


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ReportUploadActivity::class.java)
            context.startActivity(intent)
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        specialColumn()

        FocusViewUtils.scaleView(mBinding?.tvPrevious, 1)
        FocusViewUtils.scaleView(mBinding?.tvNextPage, 1)
    }

    override fun initData() {
        personalCenterViewModel.caseHistoryPatient(UserInfoManager.getPatientInfo()?.id, mPage)
        personalCenterViewModel.caseHistoryPatientLiveData.observe(this) {
            dismissLoading()
            arrayObjectAdapter.clear()
            if (mPage == 1) {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    caseHistoryList.add(MedicalRecordReport())
                    arrayObjectAdapter.addAll(0, caseHistoryList)
                    mBinding?.llBelow?.gone()
                } else {
                    isHaveNext(it.size)

                    caseHistoryList = it
                    caseHistoryList.add(0,MedicalRecordReport())
                    arrayObjectAdapter.addAll(0, caseHistoryList)

                }
            } else {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mPage-- //恢复上一次的page
                    showToast("没有下一页了")
                } else {
                    isHaveNext(it.size)
                    caseHistoryList = it
                    caseHistoryList.add(0,MedicalRecordReport())
                    arrayObjectAdapter.addAll(0, caseHistoryList)

                }
            }
        }
        LiveDataBus.get().with(CASE_REPORT_ACTION, Attach::class.java)
            .observe(this) {
                if (::oderCodeDialog.isInitialized){
                    oderCodeDialog.dismissDialog()
                }
                showToast("上传成功")
                personalCenterViewModel.caseHistoryPatient(
                    UserInfoManager.getPatientInfo()?.id,
                    mPage
                )
            }
    }

    private fun isHaveNext(number: Int) {
        if (number < 10) {
            isHaveNext = false
        } else {
            mBinding?.llBelow?.gone()
            isHaveNext = true
        }
    }

    override fun intListener() {
        mBinding?.tvPrevious?.onClick {
            if (mPage > 1) {
                mPage--
                personalCenterViewModel.caseHistoryPatient(
                    UserInfoManager.getPatientInfo()?.id,
                    mPage
                )
            } else {
                showToast("没有上一页了")
            }
        }

        mBinding?.tvNextPage?.onClick {
            if (isHaveNext) {
                mPage++
                personalCenterViewModel.caseHistoryPatient(
                    UserInfoManager.getPatientInfo()?.id,
                    mPage
                )
            } else {
                showToast("没有下一页了")
            }
        }
    }

    lateinit var oderCodeDialog: CodeDialog.Builder
    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = caseHistoryList[position]
            if(position == 0){
                if (item.id.isNullOrEmpty()) {

                    oderCodeDialog =
                        CodeDialog.Builder(this@ReportUploadActivity, CASE_ADD+getCodeUrl())
                    oderCodeDialog.show()

                } else {
                    UploadReportDetailsActivity.start(this@ReportUploadActivity, item)
                }
            }else{
                CommonMessageDialog.Builder(this@ReportUploadActivity)
                    .setTitle("选择需要的操作")
                    .setMessage("")
                    .setConfirm("查看详情")
                    .setCancel("一键转存")
                    .setonCancelListener {
                        it?.dismiss()
                        showToast("转存成功")
                    }
                    .setonConfirmListener {
                        if (item.id.isNullOrEmpty()) {

                            oderCodeDialog =
                                CodeDialog.Builder(this@ReportUploadActivity, CASE_ADD+getCodeUrl() )
                            oderCodeDialog.show()

                        } else {
                            UploadReportDetailsActivity.start(this@ReportUploadActivity, item)
                        }
                        it?.dismiss()
                    }.create().show()
            }
        }
    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {
        mBinding?.caseItem?.setNumColumns(2)
        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)

        arrayObjectAdapter = ArrayObjectAdapter(ReportUploadPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, onItemClickListener
        )

        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, caseHistoryList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
        lifecycleScope.launch {
            delay(500)
            //延迟获取焦点
            mBinding?.caseItem?.requestFocus()
        }
    }
}